<?php

namespace app\common\Api;

use think\Controller;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

/**
 * 图片上传到七牛云
 */
class UploadApi extends controller {

  protected $accessKey;
  protected $secrectKey;
  protected $bucket;   // 要上传的空间

  public function _initialize() {
    $conf = $this->getConfig();

    $this->accessKey = $conf['accessKey'];
    $this->secrectKey = $conf['secrectKey'];
    $this->bucket = $conf['bucket'];
  }

  
  //获取七牛云配置信息
  public function getConfig() {
    return config('sevenniu');
  }

  /**
   * [up2QiNiuYun 上传图片到七牛云]
   * @param $fileList  <input type='file' name='$fileList'>
   * @param $old_name  是否保存原文件名，默认false
   * @return $key 文件名  或者 错误信息
   */
  public function up2QiNiuYun($fileList, $old_name = false) {

    $file = request()->file($fileList);
//        $filePath = $file->getRealPath();
    require_once APP_PATH . '../vendor/phpqiniu/autoload.php'; //确保文件在相应的文件下
    // 构建鉴权对象 #需要填写你的 Access Key 和 Secret Key
    $auth = new Auth($this->accessKey, $this->secrectKey);
    // 生成上传 Token
    $token = $auth->uploadToken($this->bucket);
    // 要上传文件的本地路径
    $filePath = $file->getRealPath();
    $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
    // 上传到七牛后保存的文件名
    if ($old_name) {
      $key = $file->getInfo('name');
    } else {
      $key = substr(md5($file->getRealPath()), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $ext;
    }


    // 初始化 UploadManager 对象并进行文件的上传
    $uploadMgr = new UploadManager();

    // 调用 UploadManager 的 putFile 方法进行文件的上传
    list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
    if ($err !== null) {
      return ['code' => 0, 'msg' => '上传失败', 'data' => config('app_debug') ? $err : ''];
    } else {
      //返回图片名
      return $key;
    }
  }

  /**
   * 删除图片 该方法暂时不可调用
   */
  public function removeQiNiuYunImg() {

    die;
    require_once("qiniu/rs.php"); //改文件没找到 目前不能删除
    $bucket = "iceman";
    $key1 = "02df8201703161053403072.jpeg";
    $accessKey = $this->accessKey;
    $secretKey = $this->secrectKey;

    Qiniu_SetKeys($accessKey, $secretKey);
    $client = new Qiniu_MacHttpClient(null);

    $err = Qiniu_RS_Delete($client, $bucket, $key1);
    echo "====> Qiniu_RS_Delete result: \n";
    if ($err !== null) {
      var_dump($err);
    } else {
      echo "Success!";
    }
  }

}
